<?php

class Auth extends CI_Controller {
	
	function Auth()
	{
		parent::__construct();
		$this->load->model('Auth_model', '', TRUE);
	}
	
	function index()
	{
		if ($this->session->userdata('login') == TRUE)
		{
			redirect('home');
		}
		else
		{
			$this->load->view('auth_view');
		}
	}
	
	function logout(){
		//if(!$this->session->userdata('logged_in')) redirect('front/auth');
		
		$this->session->sess_destroy();
			
		redirect('auth');
	}
	

	
	function login(){
	
		$this->form_validation->set_rules('username', 'Username', 'required');
		$this->form_validation->set_rules('password', 'Password', 'required');
		$this->form_validation->set_message('required', 'Kolom %s harus diisi!');
		
		if ($this->form_validation->run() == TRUE)
		{
			$username = $this->input->post('username');
			$password = $this->input->post('password');
			if ($this->Auth_model->check_user($username, $password) == TRUE)
			{
				$query = $this->Auth_model->get_logged_user($username);
					foreach ($query as $row)
					{
						$id_user = $row->id_user;
						$id_role = $row->id_role;
					}
				$data = array(
					'login' => TRUE,
					'id_user' => $id_user,
					'id_role' => $id_role,
					'password' => $password,
					'username' => $username,
					'login_date' => date("l, d-M-Y"), 
					'login_time' => date("h:i:s A")	
				);
				$this->session->set_userdata($data);
				redirect('home');
			}
			else
			{
				$this->session->set_flashdata('error_message', 'Maaf, nama user dan/atau password Anda salah');
				redirect('auth');
			}
		} else {	
			redirect('auth');
		}
	}
	
}